package com.wanxi.listener;

import com.wanxi.dto.Constant;
import com.wanxi.service.Impl.MailTemplateService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author Li
 * @Date 2023/7/28 10:52
 */
@Component
public class RabbitMqListener implements ApplicationContextAware {
    @Autowired
    MailTemplateService mailTemplateService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Value("${spring.mail.username}")
    private String toSend;
    private static ApplicationContext context;

    @Scheduled(cron = "30 * * * * *")//启动后每30s输出一次
//    @RabbitListener(queues = Constant.MQ_QUEUE)
    public void sendToEmail() {
        Message messages = rabbitTemplate.receive(Constant.MQ_QUEUE);
//        将消息转换为String类型
        String receiveMessage = new String(messages.getBody());
        if(receiveMessage!=null){
            mailTemplateService.sendHtmlMail(toSend, "建议信息", receiveMessage);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  context = applicationContext;
    }
}
